﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Codemonk.Updater.Client.Wpf
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Loaded += MainWindow_Loaded;
        }
        private void Dispatche(Action action)
        {
            Dispatcher.BeginInvoke(action);
        }
        private void AddMessage(string message)
        {
            Dispatche(new Action(() => tboxInfo.Text = string.Concat(tboxInfo.Text, "\r\n", message)));
        }
        private void CloseCurrent()
        {
            Dispatche(Close);
        }


        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            var window = sender as MainWindow;
            if (window == null) return;
            window.Loaded -= MainWindow_Loaded;
            Action<Exception> error = ex =>
            {
                MessageBox.Show(ex.Message);
                CloseCurrent();
            };
            window.AddMessage("检查更新...");
            Codemonk.Updater.Client.Common.Updater.Check(error, m =>
            {
                var builder = new StringBuilder("服务端文件列表\r\n");
                var collection = m.Items;
                foreach (var item in collection) builder.AppendLine(item.Name);
                window.AddMessage(builder.ToString());
                builder.Clear();
                Codemonk.Updater.Client.Common.Updater.Update(m, error,
                    file => window.AddMessage(string.Concat("异步下载文件", file)),
                    (b, f) => window.AddMessage(string.Concat("下载文件", b ? "成功" : "失败", f)),
                    () =>
                    {
                        window.AddMessage("启动程序");
                        Codemonk.Updater.Client.Common.Updater.Start(m.EntryPoint);
                        CloseCurrent();
                    });
            });
        }

    }
}
